<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="联系人:" prop="person">
        <el-input v-model="formData.person" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话:" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="公司名称:" prop="company">
        <el-input v-model="formData.company" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="咨询的服务:" prop="service">
        <el-select v-model="formData.service" clearable placeholder="请选择咨询的服务">
          <el-option v-for="item in serviceList" :key="item.label" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as TestCommitApi from '@/api/commit'

defineOptions({ name: 'ConsultForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({} as any)
const formRules = reactive({
  person: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  company: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  service: [{ required: true, message: '咨询的服务不能为空', trigger: 'change' }]
})
// 服务下拉列表
const serviceList = ref([] as any)
// 提测服务下拉
const getService = async () => {
  let res = await TestCommitApi.getTestItems()
  let result = [] as any
  res.forEach((item) => {
    result.push(...item.testItems)
  })
  serviceList.value = result
}

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  dialogTitle.value = '测试服务咨询'
  resetForm()
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    person: '',
    phone: '',
    company: '',
    service: ''
  }
  formRef.value?.resetFields()
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value
    // await ProjectApi.updateProject(data)
    message.success(t('我们将在1个工作日内联系您'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 初始化 **/
onMounted(() => {
  getService()
})
</script>
